package com.eleven.mall.service.impl;

import com.eleven.mall.mapper.ManagerMapper;
import com.eleven.mall.pojo.UserIn;
import com.eleven.mall.pojo.entity.Manager;
import com.eleven.mall.pojo.entity.ManagerExample;
import com.eleven.mall.service.UserService;
import com.eleven.mall.utils.JwtUtils;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * @Auther: Rui_simple
 * @Date: 2022/10/21 09:24
 * @Description: UserServiceImpl
 * @Version 1.0.0
 */
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    ManagerMapper managerMapper;

    /**
     * 管理员登录：
     * 1、根据请求用户名和密码判断用户信息是否正确
     * 2、用户不存在 校验失败 返回null
     * 3、校验成功 生成JWT的token字符串 返回对象
     * @param user 用户名，密码
     * @return
     */
    @Override
    public Manager getUserInfo(UserIn user) {
        String username = user.getUsername();
        String password = user.getPassword();
        ManagerExample example = new ManagerExample();
        example.createCriteria().andMgNameEqualTo(username);
        List<Manager> managerList = managerMapper.selectByExample(example);
        if (managerList.size() == 0){
            //用户不存在
            return null;
        }else {
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            System.out.println(md5Password);
            Manager manager = managerList.get(0);
            if (manager.getMgPwd().equals(md5Password)){
                String token = JwtUtils.createToken(manager.getMgId().toString(),manager.getMgName());
                manager.setToken(token);
                return manager;
            }else {
                //密码错误
                return null;
            }
            /*if ("123456".equals(password)) {
                //密码正确
                Manager manager = managerList.get(0);
                String token = JwtUtils.createToken(manager.getMgId().toString(),manager.getMgName());
                manager.setToken(token);
               // System.out.println(token);
               // System.out.println(manager);
                return manager;
            } else {
                //密码错误
                return null;
            }*/
        }
    }
}
